import GlobalManager from "../../resources/util/globlaManager"

cc.Class({
    extends: cc.Component,

    properties: {
        soundClip: [cc.AudioClip],
        bgm: cc.AudioClip,
        vipLabel: cc.Label,
    },

    onLoad() {
        this.configJson = GlobalManager
        this.lobbyNet = this.node.getComponent("lobbyNetWork");
        console.log("🛠️重要配置", JSON.stringify(GlobalManager));
        this.lobbyUiInit();
        let PlayerInfo = require('./playerInfo');
        this.playerInfo = new PlayerInfo();
        this.isAutoLogin = this.playerInfo.readFromCache("isAutoLogin")
        this.playerInfo.readFromCache("sound", "true")
        this.playerInfo.ratio = GlobalManager.ratio  //比例
        this.messageJs = this.node.getChildByName("message").getComponent("message");
        this.tuisongJs = this.node.getChildByName("top").getChildByName("win_tankuang").getComponent("win_tanchuang");
        this.lobbyNet.netWorkInit(GlobalManager);  //连接服务器

        this.node.getChildByName("hall_version").getComponent(cc.Label).string = GlobalManager.hall_version;
        this.loading = this.node.getChildByName("loading");
        this.loading.active = false;

        this.shouDongLogin = false;  //是否手动登录
    },

    start() {
        this.node.getChildByName("game_loading").active = false;
        // 全屏
        // if (cc.sys.isBrowser && !this.configJson.isDebug) {
        //     this.schedule(this.ensureFullScreen, 3); // 每3秒执行一次
        // }

    },

    //点击事件
    onClick(event, target) {
        this.playClickSound();
        switch (target) {
            case "open_login"://打开登录界面
                this.openLogin();
                break;
            case "login"://登录
                this.userLogin();
                break;
            case "close_tip"://关闭提示
                this.closeTips();
                break;
            case "ok_tip"://  提示的ok按钮
                this.okTips();
                break;
            case "openreg"://打开注册界面
                this.openRegPanel();
                break;
            case "register"://注册
                this.userRegister();
                break;
            case "setting"://设置界面
                this.settingPanel();
                break;
            case "redeem"://打开提现界面
                this.openRedeemPanel();
                break;
            case "bet"://打开投注稽核界面
                this.openBetRecord();
                break;
            case "betHistory"://打开投注记录界面
                this.openBetHistory();
                break;
            case "event"://打开活动界面
                this.openEventPanel();
                break;
            case "email"://打开邮箱界面
                this.openEmailPanel();
                break;
            case "daily"://打开每日转盘
                this.openDailyPanel();
                break;
            case "quickStart":  //快速开始
                this.quickStart();
                break;
            case "kefu":  //客服
                this.openKefuPanel();
                break;
            case "firstRecharge":  //首充页面
                this.openFirstRechargePanel();
                break;
            case "shop":  //充值界面
                this.openShopPanel();
                break;
            case "vip":  //VIP界面
                this.openVIPPanel();
                break;
            case "sendGifts":  //拉人送礼界面
                this.openSendGiftsPanel();
                break;
            default:
                break;
        }
    },


    //打开绑定代理界面
    openBindAgentPanel() {
        this.openPanel("bindAgent/bindAgent_panel", "bindAgent", "bindAgentScript");
    },

    // 打开拉人送礼界面
    openSendGiftsPanel() {
        this.openPanel("sendGifts/sendGifts_panel", "sendGifts", "sendGiftsScript");
    },

    //打开VIP界面
    openVIPPanel() {
        this.openPanel("vip/vip_panel", "vip", "vipScript");
    },


    //打开充值界面
    openShopPanel() {
        this.openPanel("shop/shop_panel", "shop", "shopScript");
    },


    //打开首充界面
    openFirstRechargePanel() {
        this.openPanel("firstRecharge/firstRecharge_panel", "firstRecharge", "firstRechargeScript");
    },


    // 打开客服面板
    openKefuPanel() {
        this.openPanel("kefu/kefu_panel", "kefu", "kefuScript");
    },

    //快速开始
    quickStart() {
        this.openLoading();  //打开缓冲界面
        let isEmulator = this.isEmulator();
        if (isEmulator) {
            this.showTips("This game is not supported on emulators.");
            return;
        }
        let agentId = null;
        let inviterId = null;
        if (cc.sys.isBrowser) { // 确保是浏览器环境
            const urlParams = new URLSearchParams(window.location.search);
            inviterId = urlParams.get('inviterId'); // 从链接中获取邀请者ID
            agentId = urlParams.get('agentId'); // 从链接中获取代理ID
        }
        let deviceID = this.getDeviceID()
        let userName = this.playerInfo.readFromCache("userName");
        let passWord = this.playerInfo.readFromCache("passWord");
        let data = {
            action: "quickStart",
            username: userName,
            password: passWord,
            deviceID: deviceID,
            inviterId: inviterId,
            agentId: agentId
        }
        this.lobbyNet.sendMessage(data);
    },

    // 快速开始返回
    onQuickStart(data) {
        this.loading.active = false;
        if (data.respCode == "SUCCESS") {
            let info = data.data;
            if (info.from == "register") {
                this.playerInfo.writeToCache("userName", info.username)
                this.playerInfo.writeToCache("passWord", info.password)
                this.onLoginResponse(info)
            } else if (info.from == "login") {
                if (info.username && info.password) {
                    this.playerInfo.writeToCache("userName", info.username)
                    this.playerInfo.writeToCache("passWord", info.password)
                }
                this.onLoginResponse(info)
            }
        } else {
            this.showTips(`Quick start failed: ${data.message}`);
        }
    },


    //打开兑换界面
    openRedeemPanel() {
        this.openPanel("redeem/redeem_panel", "redeem", "redeemScript");
    },


    //打开每日转盘界面
    openDailyPanel() {
        this.openPanel("daily/daily_panel", "daily", "dailyScript");
    },


    //打开邮箱界面
    openEmailPanel() {
        this.node.getChildByName("top").getChildByName("btn_email").getChildByName("icon_ts").active = false;
        this.openPanel("email/email_panel", "email", "emailScript");
    },


    //打开活动界面
    openEventPanel() {
        this.openPanel("event/event_panel", "event", "eventScript");
    },


    //投注历史记录
    openBetHistory() {
        this.openPanel("betHistory/betHistory_panel", "betHistory", "betHistoryScript");
    },


    //大厅初始化
    lobbyUiInit() {
        this.node.getChildByName("Login_Panel").getChildByName("login_panel").active = false;
        this.node.getChildByName("Login_Panel").getChildByName("reg_panel").active = false;
        this.node.getChildByName("tips").active = false;
        this.node.getChildByName("Login_Panel").active = true;
        let children = this.node.getChildByName("panel_parent").children;
        for (let i = 0; i < children.length; i++) {
            children[i].active = false;
        }

        let games = this.node.getChildByName("game").children
        for (let i = 0; i < games.length; i++) {
            games[i].active = false;
        }

    },

    //连接服务器成功后
    contentSuccess() {
        // this.settingScript = this.node.getChildByName("panel_parent").getChildByName("setting").getComponent("setting");  //设置脚本
        this.gameContent = this.node.getChildByName("game_content").getComponent("gameContent");  //游戏展示界面脚本
        this.gameContent.configJson = this.configJson;
        // this.betRecordScript = this.node.getChildByName("panel_parent").getChildByName("betRecord_panel").getComponent("betRecord");

        if (!this.playerInfo.playerId) {
            this.autoLogin()  //自动登录
        } else {
            this.updateUserCoin();
        }
    },


    // 更新玩家信息
    updatePlayerInfo(data) {
        console.log(data);
        if (data.isPasswordChanged) {
            this.returnLogin();
            return;
        }
        if (data.playerId != this.playerInfo.playerId) {
            this.returnLogin();
            return;
        }
        this.playerInfo.playerCoin = data.coin / this.playerInfo.ratio;
        this.updateUserCoin();
    },

    //返回登录界面
    returnLogin() {
        let playerId = this.playerInfo.playerId;
        let data = {
            action: "loginOut",
            playerId: playerId,
        }
        this.lobbyNet.sendMessage(data);

        this.playerInfo.playerId = 0;
        this.playerInfo.playerName = 0;
        this.playerInfo.playerCoin = 0;
        let loginPanel = this.node.getChildByName("Login_Panel");
        this.showPanel(loginPanel);
        cc.audioEngine.pauseMusic();
        // this.playerInfo.isAutoLogin = "false";
        // this.playerInfo.writeToCache("isAutoLogin", this.playerInfo.isAutoLogin);
    },

    //更新配置
    onGetConfig(data) {
        if (data.respCode == "SUCCESS") {
            let info = data.data.config;
            //游戏信息
            this.playerInfo.gameInfo = data.data.games
            this.gameContent.loadGameIcon(this.playerInfo.gameInfo);

            //跑马灯通知信息
            this.playerInfo.message = data.data.message;

            //vip奖励信息
            this.playerInfo.vipBonus = JSON.parse(data.data.vipBonus);

            if (this.playerInfo.message.length > 0) {
                this.messageJs.onGetMessage();  //获取消息后展示消息
            }
        }
    },

    //打开投注稽核界面
    openBetRecord() {
        this.openPanel("bet/betRecord_panel", "betRecord", "betRecordScript");
    },

    //点击声音
    playClickSound(bool) {
        if (this.playerInfo.sound == "false") {
            return;
        }
        cc.audioEngine.play(this.soundClip[0], false, 1);
    },

    playBgm() {
        cc.audioEngine.pauseMusic();
        if (this.playerInfo.sound == "true") {
            cc.audioEngine.playMusic(this.bgm, true);  //播放背景音乐
        }
    },

    pauseMusic() {
        cc.audioEngine.pauseMusic();
    },

    //加载头像
    loadHeadPhoto() {
        let head = this.node.getChildByName("top").getChildByName("headBg").getChildByName("tx_head3")
        let sprite = head.getComponent(cc.Sprite);
        const imagePath = "image/head/tx_head" + this.playerInfo.playerHead;
        const bundle = cc.assetManager.getBundle("hall");
        if (!bundle) {
            cc.error("未找到 bundle：hall");
            return;
        }
        bundle.load(imagePath, cc.SpriteFrame, (err, spriteFrame) => {
            if (err) {
                cc.error("加载头像失败：" + (err.message || err));
                return;
            }
            if (!head || !head.isValid) return;
            sprite.spriteFrame = spriteFrame;
        });
    },
    //自动登录
    autoLogin() {
        let isEmulator = this.isEmulator();
        if (isEmulator) {
            this.showTips("This game is not supported on emulators.");
            return;
        }
        if (this.isAutoLogin == "true") {
            let deviceID = this.getDeviceID()
            let userName = this.playerInfo.readFromCache("userName");
            let passWord = this.playerInfo.readFromCache("passWord");
            let data = {
                action: "login",
                username: userName,
                password: passWord,
                deviceID: deviceID

            }
            this.lobbyNet.sendMessage(data);
        }
    },

    //设置界面
    settingPanel() {
        this.openPanel("setting/setting", "setting", "settingScript")
    },

    //打开注册界面
    openRegPanel() {
        let reg_panel = this.node.getChildByName("Login_Panel").getChildByName("reg_panel");
        if (reg_panel.active) {
            this.hidePanel(reg_panel);
            return;
        }
        this.showPanel(reg_panel);
    },

    //注册方法
    userRegister() {
        let reg_panel = this.node.getChildByName("Login_Panel").getChildByName("reg_panel");
        let userName = reg_panel.getChildByName("accountEditBox").getComponent(cc.EditBox).string;
        let passWord = reg_panel.getChildByName("passwordEditBox").getComponent(cc.EditBox).string;
        let passWord2 = reg_panel.getChildByName("confirmEditBox").getComponent(cc.EditBox).string;
        if (userName == "") {
            this.showTips("Pleasefill in your account name.");
        } else if (passWord == "") {
            this.showTips("Please fill in your password.");
        } else if (passWord != passWord2) {
            this.showTips("The two passwords are inconsistent.");
        }

        passWord = this.forMd5(passWord);
        let data = {
            action: "reg",
            username: userName,
            password: passWord,
        }
        this.lobbyNet.sendMessage(data);
    },

    //注册响应
    onRegResponse(data) {
        if (data.respCode == "FAIL") {
            this.showTips(data.data);
        } else if (data.respCode == "SUCCESS") {
            this.showTips("Registered successfully, please log in.");
            this.node.getChildByName("Login_Panel").getChildByName("reg_panel").active = false;
            let login_panel = this.node.getChildByName("Login_Panel").getChildByName("login_panel");
            login_panel.getChildByName("accountEditBox").getComponent(cc.EditBox).string = data.data.username;
        }
    },

    //打开登录界面
    openLogin() {
        let login_panel = this.node.getChildByName("Login_Panel").getChildByName("login_panel");
        if (login_panel.active) {
            this.hidePanel(login_panel);
            return;
        }
        this.showPanel(login_panel);
    },

    //用户登录方法
    userLogin() {
        let isEmulator = this.isEmulator();
        if (isEmulator) {
            this.showTips("This game is not supported on emulators.");
            return;
        }
        let login_panel = this.node.getChildByName("Login_Panel").getChildByName("login_panel");
        this.userName = login_panel.getChildByName("accountEditBox").getComponent(cc.EditBox).string;
        let passWord = login_panel.getChildByName("passwordEditBox").getComponent(cc.EditBox).string;
        this.passWord = this.forMd5(passWord);
        if (this.userName == "") {
            this.showTips("Please fill in your account name.");
            return;
        }
        if (this.passWord == "") {
            this.showTips("Please fill in your password.");
            return;
        }
        this.shouDongLogin = true;
        let data = {
            action: "login",
            username: this.userName,
            password: this.passWord,
        }
        this.lobbyNet.sendMessage(data);
    },

    //登录响应
    onLoginResponse(data) {

        if (data.respCode == "FAIL") {
            this.showTips(`Auto login failed: ${data.message}`);
        } else if (data.respCode == "SUCCESS") {
            if (this.shouDongLogin) {
                this.playerInfo.writeToCache("userName", this.userName)
                this.playerInfo.writeToCache("passWord", this.passWord)
            }
            let info = data.data.player;
            let email = data.data.email;
            let daily = data.data.daily;
            let isReceive = daily[0].is_receive;
            for (let i = 0; i < email.length; i++) {
                const element = email[i];
                if (!element.read) {
                    this.node.getChildByName("top").getChildByName("btn_email").getChildByName("icon_ts").active = true;
                    break;
                }
            }
            this.lobbyUiInit();
            this.node.getChildByName("Login_Panel").active = false;
            this.playerInfo.playerId = info.playerId;
            this.playerInfo.playerName = info.username;
            this.playerInfo.playerCoin = info.coin / this.configJson.ratio;
            this.playerInfo.playerHead = info.headId;
            this.playerInfo.vip = info.vip
            this.playerInfo.emailInfo = email;
            this.playerInfo.totalRecharge = info.total_recharge
            this.playerInfo.isGuest = info.isGuest
            this.playerInfo.isFirstRecharge = info.is_first_recharge
            this.playerInfo.agentId = info.agent_id
            this.playerInfo.inviterId = info.inviter_id
            this.playerInfo.writeToCache("playerHead", this.playerInfo.playerHead)
            this.afterLogin(); //登录成功后执行

            if (!info.agent_id && !info.inviter_id) {
                this.openBindAgentPanel();   //打开绑定代理界面
            } else if (!info.is_first_recharge) {
                this.openFirstRechargePanel();
            } else if (!isReceive) {
                this.openDailyPanel();
            }
        }
    },

    //登录成功后执行
    afterLogin() {
        let top = this.node.getChildByName("top");
        top.getChildByName("playerName").getComponent(cc.Label).string = this.playerInfo.playerName;
        top.getChildByName("playerId").getComponent(cc.Label).string = "ID:" + this.playerInfo.playerId;
        this.playerInfo.writeToCache("isAutoLogin", "true")
        this.playerInfo.isAutoLogin = "true"
        this.playBgm(); //播放背景音乐
        this.loadHeadPhoto();  //加载头像
        this.updateUserCoin(); //更新金币

        this.vipLabel.string = this.playerInfo.vip;

        //更新一下提现订单
        let data = {
            action: "getOrderRecord",
            playerId: this.playerInfo.playerId
        }
        this.lobbyNet.sendMessage(data);
    },

    //更新金币
    updateUserCoin() {
        this.loading.active = false
        let targetCoin = parseFloat(this.playerInfo.playerCoin);
        let playerCoinLabel = this.node
            .getChildByName("top")
            .getChildByName("coinBg")
            .getChildByName("playerCoin")
            .getComponent(cc.Label);

        let duration = 1.0; // 动画持续时间
        let startCoin = 0;
        let currentObj = { value: startCoin };

        cc.tween(currentObj)
            .to(duration, { value: targetCoin }, {
                easing: 'sineOut',
                onUpdate: () => {
                    playerCoinLabel.string = currentObj.value.toFixed(2);
                }
            })
            .start();
    },

    //新邮件
    onNewMailResponse(data, isRecharge) {
        if (isRecharge) {
            if (this.shopScript) {
                this.shopScript.node.getChildByName("top").getChildByName("btn_email").getChildByName("icon_ts").active = true;
                this.shopScript.handelRight2(true);
            }
            this.showTips("Top-up successful. Please check your email to claim your coins.");
        }
        let info = {
            action: "getTotalRecharge", //查询总充值 后加：查询首充 名字就不改了  后加 查询余额
            playerId: this.playerInfo.playerId
        }
        this.lobbyNet.sendMessage(info);

        this.node.getChildByName("top").getChildByName("btn_email").getChildByName("icon_ts").active = true;
        this.playerInfo.emailInfo = data.data;
        if (this.emailScript) {
            this.emailScript.sortEmail();
            this.emailScript.setEmail();
        }
    },


    //显示提示信息
    showTips(tips, callback) {
        let tipPanel = this.node.getChildByName("tips");
        if (callback) {
            tipPanel.callback = callback;
        } else {
            tipPanel.callback = null;
        }
        let tipLabel = tipPanel.getChildByName("tipBg").getChildByName("label").getComponent(cc.Label);
        tipLabel.string = tips;
        this.showPanel(tipPanel);
    },

    //关闭提示
    closeTips() {
        let tipPanel = this.node.getChildByName("tips");
        this.hidePanel(tipPanel);
    },

    //提示界面的OK按钮
    okTips() {
        let tipPanel = this.node.getChildByName("tips");
        if (tipPanel.callback) {
            tipPanel.callback(); // 调用回调
        } else {
            this.hidePanel(tipPanel);
        }
    },

    //显示面板(大小)
    showPanel(panelNode) {
        panelNode.active = true;  // 显示面板
        panelNode.scale = 0;  // 初始设置为缩小状态

        cc.tween(panelNode)
            .to(0.5, { scale: 1 }, { easing: 'backOut' })
            .start();
    },

    //隐藏面板(大小)
    hidePanel(panelNode, callback) {
        cc.tween(panelNode)
            .to(0.3, { scale: 0 }, { easing: 'backIn' })
            .call(() => {
                panelNode.active = false;  // 动画结束后隐藏面板

                // 如果 callback 是一个函数才执行，避免为 null 或其他类型报错
                if (callback && typeof callback === 'function') {
                    callback();
                }
            })
            .start();
    },

    //显示面板(透明度)
    showPanel2(panelNode) {
        panelNode.active = true;  // 显示面板
        panelNode.opacity = 0;  // 初始设置为完全透明

        cc.tween(panelNode)
            .to(0.5, { opacity: 255 }, { easing: 'sineOut' })  // 渐显到完全不透明
            .start();
    },

    //隐藏面板(透明度)
    hidePanel2(panelNode) {
        cc.tween(panelNode)
            .to(0.5, { opacity: 0 }, { easing: 'sineIn' })  // 渐隐到完全透明
            .call(() => {
                panelNode.active = false;  // 动画结束后隐藏面板
            })
            .start();
    },

    //打开面板公用方法
    openPanel(prefabPath, componentName, scriptFieldName) {
        const bundle = cc.assetManager.getBundle("panel");
        if (!bundle) {
            cc.error("未找到 panel");
            return;
        }

        bundle.load(prefabPath, cc.Prefab, (err, prefab) => {
            if (err) {
                console.error(`加载预制体失败：${prefabPath}`, err);
                return;
            }

            const node = cc.instantiate(prefab);
            this[scriptFieldName] = node.getComponent(componentName);  // 设置脚本引用
            const panelParent = this.node.getChildByName("panel_parent");
            panelParent.addChild(node);
            this.showPanel(node);
        });
    },


    //md5加密
    forMd5(str) {
        let md5 = require("md5").getInstant;
        let hash = md5.hex_md5(str).toUpperCase();
        return hash;
    },

    //复制文本
    copyText(text) {
        if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
            try {
                jsb.reflection.callStaticMethod(
                    "org/cocos2dx/javascript/ClipboardHelper",
                    "copyToClipboard",
                    "(Ljava/lang/String;)V",
                    text
                );
                this.showTips("Copy successful");
            } catch (e) {
                console.error('原生复制失败', e);
                this.showTips("Copy failed");
            }
        } else if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(() => {
                this.showTips("Copy successful");
            }).catch(err => {
                console.error('复制失败', err);
                this.showTips("Copy failed");
            });
        } else {
            // 兼容旧浏览器的 execCommand 方法（已废弃但仍支持）
            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed';  // 防止页面滚动
            textarea.style.opacity = '0';
            document.body.appendChild(textarea);
            textarea.focus();
            textarea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    this.showTips("Copy successful");
                } else {
                    console.error('兼容模式复制失败');
                    this.showTips("Copy failed");
                }
            } catch (err) {
                console.error('兼容模式复制异常', err);
                this.showTips("Copy failed");
            }

            document.body.removeChild(textarea);
        }
    },

    // 模拟器检测
    isEmulator() {
        console.log("模拟器检测开始...");

        console.log(this.configJson.isEmulator);

        if (!this.configJson.isEmulator) {
            return false;
        }

        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isNative && typeof jsb !== 'undefined' && jsb.reflection) {
            try {
                global.bEmulator = jsb.reflection.callStaticMethod(
                    "org/cocos2dx/javascript/AppActivity",  // Java 类路径
                    "isRunningOnEmulator",                  // 方法名
                    "()Z"                                   // 方法签名：无参返回 boolean（Z）
                );

                if (global.bEmulator) {
                    console.log("检测结果：模拟器环境");
                } else {
                    console.log("检测结果：真机环境");
                }
            } catch (e) {
                console.log("检测模拟器失败:", e);
                global.bEmulator = true;
            }
        } else {
            console.log("非 Android 或非原生平台，默认判定为真机");
            global.bEmulator = false;
        }

        return global.bEmulator;
    },

    getDeviceID() {
        // Android 原生应用
        if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isNative) {
            let androidID = jsb.reflection.callStaticMethod(
                "org/cocos2dx/javascript/AppActivity",
                "getAndroidID",
                "()Ljava/lang/String;"
            );
            console.log("Android ID:", androidID);
            return androidID;
        }
        // Web Clip 判断
        else if (cc.sys.os === cc.sys.OS_IOS && cc.sys.isBrowser && window.navigator.standalone) {
            console.log("Running as Web Clip (iOS)");
            return "ios";  // Web Clip
        }
        // 浏览器环境（Web）
        else if (cc.sys.isBrowser) {
            console.log("Running in browser");
            return "web";  // Web 浏览器
        }
        return "web";
    },


    openUrl(url) {
        if (cc.sys.isNative) {
            // 原生平台（如 Android、iOS）
            jsb.openURL(url);
        } else {
            // Web 平台
            window.open(url, "_blank");
        }
    },

    // 检查是否全屏
    ensureFullScreen() {
        const isFullScreen =
            document.fullscreenElement ||
            document.webkitFullscreenElement ||
            document.mozFullScreenElement ||
            document.msFullscreenElement;

        if (!isFullScreen) {
            const canvas = cc.game.canvas || document.getElementById('GameCanvas') || document.documentElement;

            const requestFullScreen =
                canvas.requestFullscreen ||
                canvas.webkitRequestFullscreen ||
                canvas.mozRequestFullScreen ||
                canvas.msRequestFullscreen;

            if (requestFullScreen) {
                requestFullScreen.call(canvas).then(() => {
                    // 尝试锁定横屏
                    if (screen.orientation && screen.orientation.lock) {
                        screen.orientation.lock("landscape").catch(err => {
                            console.warn("屏幕方向锁定失败：", err);
                        });
                    }
                }).catch(err => {
                    console.warn("请求全屏失败：", err);
                });
            } else {
                console.warn("此浏览器不支持全屏 API");
            }
        } else {
            console.log("已经是全屏状态");
        }
    },


    //打开缓冲界面
    openLoading(target) {
        this.loading.active = true;
        if (target == "reconnecting") {
            this.loading.getChildByName("label").active = true;
            this.loading.getChildByName("label").getComponent(cc.Label).string = "Network error, reconnecting...";
        } else {
            this.loading.getChildByName("label").active = false;
            setTimeout(() => {
                this.loading.active = false;
            }, 2000);
        }
    },

    //查询总充值返回  首充  余额
    onTotalRechargeResult(data) {
        if (data.respCode == "SUCCESS") {
            this.playerInfo.totalRecharge = data.data.total_recharge;
            this.playerInfo.isFirstRecharge = data.data.is_first_recharge;
            this.playerInfo.playerCoin = data.data.coin / this.playerInfo.ratio;
            this.updateUserCoin();
        }
    },


    //获取玩家金币
    getPlayerCoin() {
        let data = {
            action: "getPlayerCoin",
            playerId: this.playerInfo.playerId,
        }
        this.lobbyNet.sendMessage(data);
        this.openLoading();
    },

});
